# !/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:zzly
@file:views.py
@time:2020/09/08
"""
from django.db import transaction
from django.db.models import F
from rest_framework.views import APIView
from rest_framework import generics
from utils import response_ok, response_error
from apps.article.models import Article
from apps.member.models import MemberRecord
from utils.exceptions import CustomError
from utils.permission import IsMemberUser
from .serializers import ArticleAppSeializer, ArticleDetailAppSeializer
from .filters import ArticleAppFilter


class ArticleListView(generics.ListAPIView):
    '''列表'''
    queryset = Article.objects.filter(delete=False, status=True)
    serializer_class = ArticleAppSeializer

    def filter_queryset(self, queryset):
        f = ArticleAppFilter(self.request.GET, queryset=queryset)
        return f.qs


class ArticleDetailView(generics.RetrieveAPIView):
    '''详情'''
    queryset = Article.objects.filter(delete=False, status=True)
    serializer_class = ArticleDetailAppSeializer

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        Article.objects.filter(id=instance.id).update(brown_count=F('brown_count') + 1)
        return super(ArticleDetailView, self).retrieve(request, *args, **kwargs)


class ArticleLikeView(APIView):
    '''点赞'''
    permission_classes = [IsMemberUser, ]

    def get(self, request, pk):
        try:
            article = Article.get_instance_by_id(pk)
            with transaction.atomic():
                _, messgae = MemberRecord.like_operate(article, self.request.user.member)
                return response_ok(messgae)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))


class ArticleCollectView(APIView):
    '''收藏'''
    permission_classes = [IsMemberUser, ]


    def get(self, request, pk):
        try:
            article = Article.get_instance_by_id(pk)
            with transaction.atomic():
                _, messgae = MemberRecord.collect_operate(article, self.request.user.member)
                return response_ok(messgae)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
